package net.begincode.servlet.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import com.google.zxing.BarcodeFormat;
//import com.google.zxing.EncodeHintType;
//import com.google.zxing.MultiFormatWriter;
//import com.google.zxing.client.j2se.MatrixToImageWriter;
//import com.google.zxing.common.BitMatrix;
//import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
//import com.swetake.util.Qrcode;
public class ImageServlet {
	private int imgWidth = 100;
	private int imgHeight = 40;
	private int codeCount = 5;
	private int x = 0;
	private int fontHeight;
	private int codeY;
	private String fontStyle;
	private static final long serialVersionUID = 1L;

	public ImageServlet() {
		// TODO Auto-generated constructor stub
	        x = imgWidth / (codeCount + 1);
	        fontHeight = imgHeight - 2;
	        codeY = imgHeight - 12;
	}

	public void getCheckCode(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		HttpSession session = request.getSession();

		// 在内存中创建图象
		BufferedImage image = new BufferedImage(imgWidth, imgHeight,
				BufferedImage.TYPE_INT_RGB);

		// 获取图形上下文
		Graphics2D g = image.createGraphics();

		// 生成随机类
		Random random = new Random();

		// 设定背景色
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, imgWidth, imgHeight);

		// 设定字体
		g.setFont(new Font(fontStyle, Font.PLAIN + Font.ITALIC, fontHeight));

		// 画边框
		g.setColor(new Color(55, 55, 12));
		g.drawRect(0, 0, imgWidth - 1, imgHeight - 1);

		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 160; i++) {
			int x = random.nextInt(imgWidth);
			int y = random.nextInt(imgHeight);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		// 取随机产生的认证码(4位数字)
		String sRand = "";
		int red = 0, green = 0, blue = 0;
		for (int i = 0; i < codeCount; i++) {
			red = random.nextInt(255);
			green = random.nextInt(255);
			blue = random.nextInt(255);
			int wordType = random.nextInt(3);
			char retWord = 0;
			switch (wordType) {
			case 0:
				retWord = this.getSingleNumberChar();
				break;
			case 1:
				retWord = this.getLowerOrUpperChar(0);
				break;
			case 2:
				retWord = this.getLowerOrUpperChar(1);
				break;
			}
			sRand += String.valueOf(retWord);
			g.setColor(new Color(red, green, blue));
			g.drawString(String.valueOf(retWord), (i) * x, codeY);

		}
		// 将认证码存入cookie
		Cookie randCookie = new Cookie("rand", sRand);
		randCookie.setMaxAge(5*60);   //验证码暂存5分钟
		randCookie.setPath("/");
		response.addCookie(randCookie);
		// 图象生效
		g.dispose();
		ServletOutputStream responseOutputStream = response.getOutputStream();
		// 输出图象到页面
		ImageIO.write(image, "JPEG", responseOutputStream);

		// 以下关闭输入流！
		responseOutputStream.flush();
		responseOutputStream.close();
	}

	Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private char getSingleNumberChar() {
		Random random = new Random();
		int numberResult = random.nextInt(10);
		int ret = numberResult + 48;
		return (char) ret;
	}

	private char getLowerOrUpperChar(int upper) {
		Random random = new Random();
		int numberResult = random.nextInt(26);
		int ret = 0;
		if (upper == 0) {// 小写
			ret = numberResult + 97;
		} else if (upper == 1) {// 大写
			ret = numberResult + 65;
		}
		return (char) ret;
	}
//	
//	
//	//二维码生成  直接输出
//	public void getTwoCode(HttpServletRequest request,
//			HttpServletResponse response) throws IOException {
//		
//		response.setContentType("image/jpeg");
//		response.setHeader("Pragma", "No-cache");
//		response.setHeader("Cache-Control", "no-cache");
//		response.setDateHeader("Expires", 0);
//		HttpSession session = request.getSession();
//
//		// 在内存中创建图象
//		BufferedImage image = new BufferedImage(imgWidth, imgHeight,
//				BufferedImage.TYPE_INT_RGB);
//		
//		ServletOutputStream responseOutputStream = response.getOutputStream();
//		 Hashtable<Object, Object> hints = new Hashtable<Object, Object>();
//	        // 指定纠错等级
//	        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
//	        // 指定编码格式
//	        hints.put(EncodeHintType.CHARACTER_SET, "GBK");
//	        try {
//	        	
//	            BitMatrix bitMatrix = new MultiFormatWriter().encode("www.baidu.com",  BarcodeFormat.QR_CODE, 300, 300, hints);
//	        	MatrixToImageWriter.writeToStream(bitMatrix, "png", responseOutputStream);
//	        } catch (Exception e) {
//	            e.printStackTrace();
//	        }
//
//
//		
//
//		// 以下关闭输入流！
//		responseOutputStream.flush();
//		responseOutputStream.close();
//	}
//	
//	//彩色logo二维码
//	public static void getQrcodeImgByContents(String contents, String imgPath) {
//		int width = 140;
//		int height = 140;
//		try {
//			Qrcode qrcode = new Qrcode();
//		    // 设置二维码排错率，可选L(7%)、M(15%)、Q(25%)、H(30%)，排错率越高可存储的信息越少，但对二维码清晰度的要求越小  
//
//			qrcode.setQrcodeErrorCorrect('Q');
//			qrcode.setQrcodeEncodeMode('B');
//			// 设置设置二维码尺寸，取值范围1-40，值越大尺寸越大，可存储的信息越大
//
//			qrcode.setQrcodeVersion(7);
//
//			BufferedImage bufImg = new BufferedImage(width, height,
//					BufferedImage.TYPE_INT_BGR);
//
//			Graphics2D gs = bufImg.createGraphics();
//			gs.setBackground(Color.WHITE);
//			gs.clearRect(0, 0, width, height);
//			gs.setColor(Color.BLACK);
//			//偏移量
//
//			int pixoff = 2;
//
//			byte[] contentBytes = contents.getBytes("UTF-8");
//			if (contentBytes.length != 0 && contentBytes.length < 120) {
//				boolean[][] codeOut = qrcode.calQrcode(contentBytes);
//				for (int i = 0; i < codeOut.length; i++) {
//					for (int j = 0; j < codeOut.length; j++) {
//						if (codeOut[j][i]) {
//							gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
//						}
//					}
//				}
//			} else {
//				System.out.println("大小超出限制");
//			}
//			Image img = ImageIO.read(new File("d:\\logo.png"));//实例化一个Image对象。
//
//			gs.drawImage(img, 45, 45, 50,50, null);
//			
//			
//			gs.dispose();
//			bufImg.flush();
//			File imgFile = new File(imgPath);
//			ImageIO.write(bufImg, "png", imgFile);
//			System.out.println("二维码生成成功！");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	public static void main(String[] args) {
//		getQrcodeImgByContents("http://weixin.qq.com/r/snXJ0S7EfnMBrWqy9yCg", "d:\\1.png");
	}
}
